import React, {useEffect,useCallback} from 'react';
import { Rule } from 'rc-field-form/lib/interface';
import {Form, Input, Button, Space, message} from 'antd';
import {connect,ConnectedProps} from "react-redux";
import {nanoid} from 'nanoid';
import {setToken , setUserInfo} from '@/redux/modules/global/action'

interface propsType{
    changeModalType:(type:boolean)=>void;
    modalOpen:boolean;
}

function Formpwd(props:MyComponentProps) {
    let {setToken, setUserInfo, global, modalOpen } = props
    const [pwdForm] = Form.useForm();
    const fillForm = useCallback(() => {
        pwdForm.setFieldsValue({ oldPassword: global.userInfo.password, password: '', password1: '' });
    }, [pwdForm, global.userInfo.password]);
    useEffect(()=>{
        if(modalOpen)fillForm()
    },[modalOpen,fillForm])

    const layout = {
        labelCol: { span: 8 },
        wrapperCol: { span: 16 },
    };
    const tailLayout = {
        wrapperCol: { offset: 17, span: 7 },
    };
    const onFinish = () => {
       pwdForm.validateFields().then(()=>{
           let password = pwdForm.getFieldValue('password')
           setToken(nanoid())
           setUserInfo({
               ...global.userInfo,
               password:password
           })
           props.changeModalType(false)
           message.success("修改成功！");
       })
    }
    const resetForm = () => {
       pwdForm.resetFields()
       props.changeModalType(false)
    }

    // const fillForm = () => {
    //     pwdForm.setFieldsValue({ oldPassword:global.userInfo.password,password:'',password1:''});
    // }

    const validatorPwd = (rule:Rule, value:any, callback:(error?:string)=>void) => {
        // rule是当前的验证规则对象
        // value是需要验证的字段值
        // callback是当验证完成后需要调用的回调函数，用于报告验证结果
        if(value.length>6 && value.length<10){
            const reg = new RegExp(/^(?![^a-zA-Z]+$)(?!\D+$)/);
            const flag = reg.test(value);
            if(!flag){
                callback('请输入含有字母和数字的密码')
            }else{
                callback();
            }
        }else{
            callback('请输入6-10位密码!');
        }
    }
    const validatorIsequalPwd = (rule:Rule, value:any, callback:(error?:string)=>void) => {
         let newPassword = pwdForm.getFieldValue('password')
         if(value !== newPassword){
             callback('两次密码不一致')
         }else{
             callback()
         }
    }

    return (
        <div>
            <Form
                {...layout}
                form={pwdForm}
                name="edit-pwd"
                onFinish={onFinish}
                style={{ maxWidth: 600 }}
            >
                <Form.Item name="oldPassword" label="旧密码" rules={[{ required: true,message: '请输入旧密码!'}]}>
                    <Input.Password disabled/>
                </Form.Item>
                <Form.Item name="password" label="新密码" rules={[{ required: true,message: '请输入新密码!'},{validator: (rule, value, callback) => {validatorPwd(rule, value, callback)}}]}>
                    <Input.Password/>
                </Form.Item>
                <Form.Item name="password1" label="确认新密码" rules={[
                    { required: true,message: '请输入新密码!'},
                    {validator: (rule, value, callback) => {validatorIsequalPwd(rule, value, callback)}},
                ]}>
                    <Input.Password/>
                </Form.Item>
                <Form.Item {...tailLayout}>
                    <Space>
                        <Button htmlType="button" onClick={resetForm}>
                            取消
                        </Button>
                        <Button type="primary" htmlType="submit">
                            确定
                        </Button>
                    </Space>
                </Form.Item>
            </Form>
        </div>
    );
}

const mapStateToProps = (state:any)=>{
    return {
        global:state.global
    }
};
const mapDispatchToProps = { setToken,setUserInfo}
let connector = connect(mapStateToProps,mapDispatchToProps)
type PropsFromRedux = ConnectedProps<typeof connector>;
// 定义组件的全部 props 类型，包括父组件传递的和 connect 传递的
type MyComponentProps = PropsFromRedux & propsType;

export default connector(Formpwd);
